//
// Created by v on 19-4-22.
//

#include <getopt.h>
#include <stdlib.h>
#include <unistd.h>

#include "CMAutoTestCommand.h"
#include "CMFifoHandler.h"
#include "utils/cm_logprint.h"

CMLogPrint logPrint;

static void open_fifo_write()
{
    CMFifoHandler::getInstance()->open("/tmp/autotest.fifo");
    CMFifoHandler::getInstance()->write("test", "this is test write");
}

int main(int argc, char **args)
{
    CMAutoTestCommand tcmd;
    tcmd.initAllCmd();

    bool   autotestall       = false;
    bool   reboot_after_done = false;
    int    reboot_wait_sec   = 0;
    char * cmd               = NULL;
    int    argc_c            = argc - 1;
    char **argc_p            = args + 1;
    int    c                 = 0;
    while ((c = getopt(argc, args, "fhac:r:")) != -1)
    {
        switch (c)
        {
        case 'a':
            autotestall = true;
            argc_c -= 1;
            argc_p++;
            break;
        case 'c':
            cmd = optarg;
            argc_c -= 2;
            argc_p++;
            argc_p++;
            break;
        case 'r':
            reboot_after_done = true;
            reboot_wait_sec   = atoi(optarg);
            argc_c -= 2;
            argc_p++;
            argc_p++;
            break;
        case 'h':
            tcmd.showUsage(args[0]);
            exit(0);
            break;
        case 'f':
            open_fifo_write();
            argc_c -= 1;
            argc_p++;
        default:
            break;
        }
    }

    LOGD("Test with autotest all [%d] cmd [%s]\n", autotestall,
         cmd == NULL ? "" : cmd);
    // Create it when test program run
    system("touch /sdcard/ccautotest");

    if (autotestall)
    {
        tcmd.testAllAuto();
    }
    else
    {
        if (!cmd)
            return -1;
        int ret = tcmd.testStart(cmd, argc_c, argc_p);
        LOGD("test result %d\n", ret);
    }

    if (reboot_after_done)
    {
        LOGD("enable power off , wait for [%d]\n", reboot_wait_sec);
        sleep(reboot_wait_sec);
        CMFifoHandler::getInstance()->write("key", "poweroff");
        sleep(30);
        system("reboot");
    }
    CMFifoHandler::getInstance()->close();
    LOGD("benewautotest exit\n");
    return 0;
}
